<template>
  <div class="bim-sdk-box">
    <div
      class="bim-model-box"
      id="bimContainer"
      ref="bimContainer"></div>
      <div>{{  testData }}</div>
    <template v-if="isLoad">
      <template v-if="type === 'select'">
        <div
          class="ensure-btn"
          @click="ensure">确认</div>
        <div class="ensure-btn choose-model flex-row-center-center">
          <div
            class="ensure-btn-item"
            v-if="!markInfo"
            @click="markActive">选择模型</div>
          <div
            v-else
            class="ensure-btn-item"
            @click="delMark">删除</div>
        </div>  
      </template>
    </template>
    <div
      v-if="type === 'preview'"
      class="ensure-btn"
      @click="goBack">返回</div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import axios from "axios"

interface MarkInfo {
  id: string
  areaId: { x: number, y: number, z: number }
  areaUp: string
  areaEye: string
}

let viewer3d: any = null
let markTool: any = null
let markManagerTool: any = null
const viewerResize = () => {
  if (viewer3d) viewer3d.reSize();
};
// const effectOpt = window.ECHO.Constant.EffectType.Render + window.ECHO.Constant.EffectType.Sky

// 文档：http://www.xietongbao.com.cn/monge/mongeDoc
@Component
export default class Home extends Vue {
  @Ref() bimContainer!: HTMLDivElement
  public models: string[] = [] // model urls
  public isLoad = false
  public type = "select" // priview（预览）select（选择）
  public markInfo: MarkInfo | null = null
  public testData = ""
  mounted() {
    console.log('---模型初始化---')
    this.testData = window.navigator.userAgent
    if (typeof window.Monge !== 'undefined') {
      console.log('defined Monge...');
      this.loadInfo();
    } else {
      console.log('undefined Monge...');
      // 动态引入较大类库避免影响页面展示
      const script = document.createElement('script')
      // view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
      script.src = 'static/plugin/monge/Monge.js'
      script.onload =  () => {
        this.loadInfo()
      }
      document.head.appendChild(script)
    }
  }

  beforeDestroy() {
    window.removeEventListener("resize", viewerResize);
  }

  loadInfo() {
    console.log('---loadInfo---')
    this.init()
    // 调试
    // this.initModel([
    //   "https://elec-admin-test-server.aecmate.com/elec_operation/images/project/model/lightFile/1645267668325093377/1645270985025507330/lightFile/",
    //   "https://elec-admin-test-server.aecmate.com/elec_operation/images/project/model/lightFile/1645267668325093377/1645270961856172034/lightFile/",
    //   "https://elec-admin-test-server.aecmate.com/elec_operation/images/project/model/lightFile/1645267668325093377/1645271255025438721/lightFile/",
    // ])
  }

  async init() {
    // http://123.56.72.49:9504/online/#/?nodeId=1645273614547881985&projectId=1645267668325093377&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJlbGVjLXVzZXIiLCJpYXQiOjE2ODExMzU3NjQsImV4cCI6MTc2NzUzNTc2NCwiaWQiOiIxNTk1MzEyOTgzMjUwMjc2MzU0IiwidXNlcm5hbWUiOiJ6aGVuZ2dvbmcifQ.laXGdwHKebXBaZn_gpdyS5H7qwFYxYQF1lORrJ6mX6o&type=select
    let domain = "https://elec-test-server.aecmate.com"
    if (window.location.href.includes("http://123.56.72.49:9504/online")) {
      domain = "https://elec-test-server.aecmate.com"
    }
    const { token, nodeId, projectId, type } = this.$route.query
    this.type = (type as string) || "preview"
    try {
      const result = await axios({
        method: 'get',
        // url: `https://elec-test-server.aecmate.com/elec_install/sys/project-node/getModelInfoById/${nodeId}/${projectId}`,
        url: `${domain}/elec_install/sys/project-node/getModelInfoById/${nodeId}/${projectId}`,
        headers: {
          token: token as string
        }
      })
      if (result?.data?.data?.items?.length) {
        let set = new Set()
        result.data.data.items.forEach((item: string) => {
          const temp = JSON.parse(item)
          temp.forEach((tmp: any) => {
            set.add(tmp.url)
          })
        })
        const models = [...set]
        this.initModel(models as string[])
      }
      console.log(result)
    } catch (err) {
      // 
    }
  }
  initModel(models: string[]) {
    window.Monge.EngineResources =
      process.env.NODE_ENV === "production" ?
        `/online/static/plugin/monge/EngineResources` :
        `/static/plugin/monge/EngineResources`;
    window.addEventListener("resize", viewerResize);
    this.models = models
    this.loadModels()
  }

  loadModels() {
    const option = {
      isDefaultUI: true,
      longforLoading: true,
      effect: window.Monge.EffectType3D.Render |
        window.Monge.EffectType3D.Sky
        // window.Monge.EffectType3D.FouLine |
        // window.Monge.EffectType3D.SSAO |
        // window.Monge.EffectType3D.FXAA |
        // window.Monge.EffectType3D.Shadow
    };
    viewer3d = new window.Monge.Viewer3D("bimContainer", option);
    this.bimContainer.addEventListener(window.Monge.EventType.attributeDone, () => {
      this.isLoad = true
      // markTool.deactive(); // 关闭工具
      console.log('模型加载完成')
    });

    markTool = new window.Monge.Mark3D(viewer3d);
    markManagerTool = new window.Monge.MarkManager3D(viewer3d);
    
    viewer3d.load(this.models);
  }

  markActive() {
    if(this.markInfo || !this.isLoad) { return }
    const annotate = () => {   
      markTool.active({ 
        color: 0xff0000,
        callback: (type: string, data: any) => {
          console.log('类型*************', type);
          console.log('数据*************', data);
          if(data.modelUrl){
            this.markInfo = {
              id: data.id,
              areaId: data.point,
              areaUp: data.modelUrl,
              areaEye: data.componentId
            }
          } else {
            markManagerTool.clear();
            setTimeout(() => {
              annotate();
            }, 1000);
          }
        }
      }); 
    }
    annotate();
  }

  ensure() {
    console.log("@@bimsdk result@@", JSON.stringify(this.markInfo))
    console.log("---postMessage---", window.uniCus.postMessage)
    window.uniCus.postMessage({
      data: {
        action: this.markInfo ? JSON.stringify(this.markInfo) : ""
      }
    });
  }

  delMark() {
    if (this.markInfo) { 
      markManagerTool.remove(this.markInfo.id);
      this.markInfo = null
    }
  }

  goBack() {
    window.uniCus.postMessage({
      data: {
        action: "back"
      }
    }); 
  }
}
</script> {}

<style scoped lang="scss">
.bim-sdk-box {
  position: relative;
  width: 100vw;
  height: 100vh;
  padding-top: 20px;
  box-sizing: border-box;
  background: #ededed;
}
.bim-model-box {
  width: 100%;
  height: 100%;
}

.bim-sdk-box .ensure-btn {
  position: absolute;
  width: 80px;
  height: 28px;
  line-height: 28px;
  left: 20px;
  top: 40px;
  font-size: 14px;
  border: solid 1px #dddddd;
  background-color: #ffffff;
  color: #333333;
  border-radius: 6px;
  text-align: center;
  z-index: 990;
  cursor: pointer;
}

.bim-sdk-box .ensure-btn.choose-model {
  left: 110px;
}
</style>